package service

import (
	"context"
	"time"

	"gitee.com/jiebaiyou/formflow/internal/tokenutil"
	"gitee.com/jiebaiyou/formflow/model"
)

// loginService 实现了model.LoginService接口, 提供用户登录相关的业务逻辑
// 包括用户查询和令牌生成功能
type loginService struct {
	userRepository model.UserRepository // 用户数据访问接口
	contextTimeout time.Duration        // 上下文超时时间
}

// NewLoginService 创建并返回一个实现了model.LoginService接口的实例
func NewLoginService(userRepository model.UserRepository, timeout time.Duration) model.LoginService {
	return &loginService{
		userRepository: userRepository,
		contextTimeout: timeout,
	}
}

// GetUserByEmail 根据邮箱地址查询用户信息
func (lu *loginService) GetUserByEmail(c context.Context, email string) (model.User, error) {
	// 创建一个带超时的上下文
	ctx, cancel := context.WithTimeout(c, lu.contextTimeout)
	defer cancel()
	// 调用仓库层查询用户
	return lu.userRepository.GetByEmail(ctx, email)
}

// CreateAccessToken 为用户创建访问令牌(JWT)
func (lu *loginService) CreateAccessToken(user *model.User, secret string, expiry int) (accessToken string, err error) {
	return tokenutil.CreateAccessToken(user, secret, expiry)
}

// CreateRefreshToken 为用户创建刷新令牌(JWT)
func (lu *loginService) CreateRefreshToken(user *model.User, secret string, expiry int) (refreshToken string, err error) {
	return tokenutil.CreateRefreshToken(user, secret, expiry)
}
